# 使用官方 .NET 9.0 运行时作为基础镜像
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

# 设置环境变量
ENV ASPNETCORE_URLS=http://+:80;https://+:443
ENV ASPNETCORE_ENVIRONMENT=Production

# 安装运行时依赖
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 创建非root用户
RUN useradd -m -u 1000 matrix && \
    mkdir -p /app/logs && \
    chown -R matrix:matrix /app
USER matrix

# 构建阶段
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src

# 复制csproj文件并还原依赖
COPY ["src/Matrix.ServiceDiscovery.Domain.Shared/Matrix.ServiceDiscovery.Domain.Shared.csproj", "src/Matrix.ServiceDiscovery.Domain.Shared/"]
COPY ["src/Matrix.ServiceDiscovery.Domain/Matrix.ServiceDiscovery.Domain.csproj", "src/Matrix.ServiceDiscovery.Domain/"]
COPY ["src/Matrix.ServiceDiscovery.Application.Contracts/Matrix.ServiceDiscovery.Application.Contracts.csproj", "src/Matrix.ServiceDiscovery.Application.Contracts/"]
COPY ["src/Matrix.ServiceDiscovery.Application/Matrix.ServiceDiscovery.Application.csproj", "src/Matrix.ServiceDiscovery.Application/"]
COPY ["src/Matrix.ServiceDiscovery.EntityFrameworkCore/Matrix.ServiceDiscovery.EntityFrameworkCore.csproj", "src/Matrix.ServiceDiscovery.EntityFrameworkCore/"]
COPY ["src/Matrix.ServiceDiscovery.HttpApi/Matrix.ServiceDiscovery.HttpApi.csproj", "src/Matrix.ServiceDiscovery.HttpApi/"]
COPY ["src/MatrixServiceDiscovery.HttpApi.Host/MatrixServiceDiscovery.HttpApi.Host.csproj", "src/MatrixServiceDiscovery.HttpApi.Host/"]
RUN dotnet restore "src/MatrixServiceDiscovery.HttpApi.Host/MatrixServiceDiscovery.HttpApi.Host.csproj"

# 复制所有源代码
COPY . .

# 工作目录设置为项目目录
WORKDIR "/src/src/MatrixServiceDiscovery.HttpApi.Host"

# 构建并发布应用
RUN dotnet build "MatrixServiceDiscovery.HttpApi.Host.csproj" -c Release -o /app/build
RUN dotnet publish "MatrixServiceDiscovery.HttpApi.Host.csproj" -c Release -o /app/publish /p:UseAppHost=false

# 最终运行阶段
FROM base AS final
WORKDIR /app

# 从构建阶段复制发布的应用
COPY --from=build /app/publish .

# 创建日志目录
RUN mkdir -p /app/logs

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost/health || exit 1

# 启动应用
ENTRYPOINT ["dotnet", "MatrixServiceDiscovery.HttpApi.Host.dll"]